package com.zjw.concurrency.juc.threadlocal;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.zjw.interview.juc.threadlocal.ThreadLocalDate.threadLocalDate;


/**
 * 线程池实现，threadLocal，没个threadlocal对象内保存一个对象副本，不会产生时间重复的问题
 * */
public class ThreadlocalExample_03 {

    public static void main(String[] args) {
        ExecutorService executorService = Executors.newFixedThreadPool(10);
        for (int i = 0; i < 1000; i++) {
            int finalI = i;
            executorService.submit(new Thread(new Runnable() {
                @Override
                public void run() {
                    String date = new ThreadlocalExample_03().date(finalI);
                    System.out.println(Thread.currentThread().getName() + ":" + date);
                }
            }));
        }
        executorService.shutdown();
    }

    public String date(int second){

        Date date = new Date(second * 1000);
        SimpleDateFormat simpleDateFormat =  ThreadLocalDate.threadLocalDate.get();
        String dateString = simpleDateFormat.format(date);
        return dateString;
    }
}

class ThreadLocalDate{
    public static ThreadLocal<SimpleDateFormat> threadLocalDate = new ThreadLocal<SimpleDateFormat>(){
        @Override
        protected SimpleDateFormat initialValue() {
            return new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        }
    };
}
